<template>
    <div class="alloc-menu">
      <el-card>
        <el-tree ref="menu-tree" node-key="id" :default-checked-keys="checkedKeys" :data="menu" :props="defaultProps" @node-click="handleNodeClick" show-checkbox default-expand-all></el-tree>
        <div style="margin:20px">
          <el-button @click="onReset">清空</el-button>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </div>
      </el-card>
    </div>
</template>

<script>
import { getMenuNodeList, allocateRoleMenus, getRoleMenu } from '@/services/getEditMenuInfo'
export default {
  name: 'AllocMenu',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      menu: [],
      defaultProps: {
        children: 'subMenuList',
        label: 'name'
      },
      checkedKeys: []
    }
  },
  created () {
    this.loadMenu()
    this.loadRoleMenu()
  },
  methods: {
    onReset () {
      this.$refs['menu-tree'].setCheckedKeys([])
    },
    setCheckedKeys (menu) {
      menu.forEach(element => {
        // 节点是false直接跳过
        if (!element.selected) {
          return
        }
        // 如果有子节点，那么检测子节点
        if (element.subMenuList) {
          return this.setCheckedKeys(element.subMenuList)
        }
        // 使用push方法会让页面频繁刷新，导致数据传了，但是界面不刷新
        // this.checkedKeys.push(element.id)
        this.checkedKeys = [...this.checkedKeys, element.id]
      })
    },
    async loadRoleMenu () {
      const { data } = await getRoleMenu(this.roleId)
      if (data.code === '000000') {
        this.setCheckedKeys(data.data)
      }
    },
    async loadMenu () {
      const { data } = await getMenuNodeList()
      if (data.code === '000000') {
        this.menu = data.data
      }
    },
    async onSubmit () {
      // console.log(this.$refs['menu-tree'].getCheckedKeys())
      // console.log(this.$refs['menu-tree'].getCheckedNodes())
      const { data } = await allocateRoleMenus({ roleId: this.roleId, menuIdList: this.$refs['menu-tree'].getCheckedKeys() })
      if (data.code === '000000') {
        this.$message.success('分配菜单成功')
        this.$router.push({ name: 'role' })
      }
    }
  }
}
</script>

<style lang="scss" scoped ></style>
